package org.duang.http.auth;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.duang.config.Config;
import org.duang.http.util.HttpUtil;
import org.duang.kit.Digests;
import org.duang.kit.ToolsKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 签名
 * 
 * @author laotang
 */
public class Signature {
	
	private static Logger logger = LoggerFactory.getLogger(Signature.class);
	public final static String DUANG_SGIN_KEY_FIELD = "duangkey";
	public final static String DUANG_SGIN_RESULT_FIELD = "duangsgin";

	/**
	 * 根据paramMap里的内容值及密钥，生成MD5加密字符串
	 * @param paramMap
	 * @return
	 */
	public static String getSign(Map<String, Object> paramMap) {
		StringBuilder sb = new StringBuilder(createParamString(paramMap));
		InputStream input = ToolsKit.string2InputStream(sb.toString(), Config.getEncoding());
		if (ToolsKit.isNotEmpty(input)) {
			try {
				String result = Digests.md5toString(input);
				sb.append("&").append(DUANG_SGIN_RESULT_FIELD).append("=").append(result);
				return sb.toString();		
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";		
	}
	
	/**
	 * 只返回加密后的字符串
	 * @param paramMap
	 * @return
	 */
	public static String getSignResult(Map<String, Object> paramMap) {
		StringBuilder sb = new StringBuilder(createParamString(paramMap));
		InputStream input = ToolsKit.string2InputStream(sb.toString(), Config.getEncoding());
		if (ToolsKit.isNotEmpty(input)) {
			try {
				return Digests.md5toString(input);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";		
	}
	
	/**
	 * 只返回加密后的字符串
	 * @param InputStream
	 * @return
	 */
	public static String getSignResult(InputStream content) {
		if (ToolsKit.isNotEmpty(content)) {
			try {
				return Digests.md5toString(content);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";		
	}
	
	private static String createParamString(Map<String, Object> paramMap) {
		if (ToolsKit.isEmpty(paramMap))
			throw new NullPointerException("Signature getSign paramMap is null!");
		
		StringBuilder sb = new StringBuilder();
		try {
			sb.append(HttpUtil.paramToQueryString(paramMap));
		} catch (UnsupportedEncodingException e) {
			logger.warn(e.getMessage(), e);
		}
		if (sb.length() > 0) {
			sb.append("&").append(DUANG_SGIN_KEY_FIELD).append("=").append(Config.getSignKey());
		}
		return sb.toString();
	}
	
	public static boolean validateSign(Map<String, Object> paramMap) {
		if (ToolsKit.isEmpty(paramMap))
			throw new NullPointerException("Signature validateSign paramMap is null!");
		String signKeyByResponse = paramMap.get(DUANG_SGIN_RESULT_FIELD).toString();
		if(ToolsKit.isEmpty(signKeyByResponse)) {
			// 返回的加密字符串为空,表示这个API返回的数据有可能已经被篡改
			logger.warn("response sign data is not exite!");
			return false;
		}
		paramMap.remove(DUANG_SGIN_RESULT_FIELD);
		String signKeyByFuncion = getSign(paramMap);
		if(!signKeyByResponse.equals(signKeyByFuncion)) {
			// 返回的加密字符串与生成的加密字符串不一致，表示这个API返回的数据有可能已经被篡改
			logger.warn("response sign data is not equal!"); 	
			return false;
		}
		return true;
	}
	
	public static boolean validateRequestUserAgent() {
		return false;
	}
}
